package pers.cz.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.config.Config;
import pers.cz.config.ConfigCache;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * @program: postgirl-collection-client
 * @description: RedisUtil
 * @author: Cheng Zhi
 * @create: 2022-02-07 18:16
 **/
public class RedisConfig {

    private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    static {
        Properties properties = null;
        try {
            properties = ConfigCache.getProperties();
            ConfigCache.setConfig(properties);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
    public JedisPool redisPoolFactory() {

        Map<String, String> cacheMap = Config.getConfig().getsysConfig();
        Integer maxIdle = Integer.valueOf(cacheMap.get("redis.maxIdle"));
        Integer maxWait = Integer.valueOf(cacheMap.get("redis.maxWait"));
        Boolean blockWhenExhausted = Boolean.valueOf(cacheMap.get("redis.blockWhenExhausted"));
        String host = cacheMap.get("redis.host");
        Integer port = Integer.valueOf(cacheMap.get("redis.port"));
        Integer timeout = Integer.valueOf(cacheMap.get("redis.timeout"));
        Integer maxActive = Integer.valueOf(cacheMap.get("redis.maxActive"));
        String password = cacheMap.get("redis.password");

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        jedisPoolConfig.setMaxTotal(maxActive);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);
        // Idle(空闲)时进行连接扫描
        jedisPoolConfig.setTestWhileIdle(true);
        // 表示idle object evitor两次扫描之间要sleep的毫秒数
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
        // 表示idle object evitor每次扫描的最多的对象数
        jedisPoolConfig.setNumTestsPerEvictionRun(10);
        // 表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
        jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
        return jedisPool;

    }

/*    public static void main(String[] args) throws IOException {

        RedisConfig redisUtil = new RedisConfig();
        for (int i=0; i < 10; i++) {

            Map<String, String> cacheMap = Config.getConfig().getsysConfig();

            System.out.println(cacheMap.get("redis.host"));
        }
    }*/
}
